# -*- coding: utf-8 -*-
"""
系统设置模块
"""

from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QTableWidget, 
                            QTableWidgetItem, QPushButton, QLineEdit, QLabel, 
                            QComboBox, QMessageBox, QDialog, QFormLayout, 
                            QDialogButtonBox, QTabWidget, QTreeWidget, QTreeWidgetItem)
from PyQt5.QtCore import Qt
from database import Database

class SystemSettingsWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.db = Database()
        self.init_ui()
        self.load_dictionary_data()
        self.remove_duplicate_dictionary_data()  # 清理重复数据
    
    def init_ui(self):
        """初始化用户界面"""
        layout = QVBoxLayout(self)
        
        # 创建标签页
        self.tab_widget = QTabWidget()
        
        # 字典管理标签页
        self.dict_tab = QWidget()
        self.init_dict_tab()
        self.tab_widget.addTab(self.dict_tab, "📚 字典管理")
        
        layout.addWidget(self.tab_widget)
    
    def init_dict_tab(self):
        """初始化字典管理标签页"""
        layout = QVBoxLayout(self.dict_tab)
        
        # 应用模块分类树
        self.module_tree = QTreeWidget()
        self.module_tree.setHeaderLabels(["应用模块"])
        self.module_tree.setMinimumWidth(200)
        self.module_tree.itemClicked.connect(self.on_module_item_clicked)
        layout.addWidget(self.module_tree)
        
        # 字典值表格
        self.dict_table = QTableWidget()
        self.dict_table.setColumnCount(3)
        self.dict_table.setHorizontalHeaderLabels(["🏷️ 字典名称", "📝 字典值", "📄 描述"])
        self.dict_table.setSelectionBehavior(QTableWidget.SelectRows)
        self.dict_table.setAlternatingRowColors(True)
        
        layout.addWidget(self.dict_table)
        
        # 操作按钮
        button_layout = QHBoxLayout()
        self.add_dict_button = QPushButton("➕ 添加字典值")
        self.add_dict_button.clicked.connect(self.add_dictionary_value)
        
        self.refresh_button = QPushButton("🔄 刷新")
        self.refresh_button.clicked.connect(self.load_dictionary_data)
        
        button_layout.addWidget(self.add_dict_button)
        button_layout.addWidget(self.refresh_button)
        button_layout.addStretch()
        layout.addLayout(button_layout)
        
        # 初始化模块树
        self.init_module_tree()
    
    def init_module_tree(self):
        """初始化模块树"""
        self.module_tree.clear()
        
        # 定义模块分类
        modules = {
            "IP管理": ["设备类型", "网段"],
            "资产信息管理": ["虚拟化类型"],
            "中间件管理": ["中间件类型", "中间件名称"],
            "应用系统管理": ["应用系统类型"],
            "系统账号管理": ["账号级别", "账号类型"],
            "其他": []  # 用于存放未分类的字典类型
        }
        
        # 获取所有字典类型
        try:
            conn = self.db.get_connection()
            cursor = conn.cursor()
            cursor.execute('SELECT DISTINCT dict_name FROM dictionary ORDER BY dict_name')
            all_dict_types = [row[0] for row in cursor.fetchall()]
            conn.close()
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载字典类型失败：{str(e)}")
            return
        
        # 按模块分类字典类型
        categorized = set()
        for module_name, dict_types in modules.items():
            module_item = QTreeWidgetItem(self.module_tree, [module_name])
            module_item.setData(0, Qt.UserRole, "module")
            
            # 添加预定义的字典类型
            for dict_type in dict_types:
                if dict_type in all_dict_types:
                    dict_item = QTreeWidgetItem(module_item, [dict_type])
                    dict_item.setData(0, Qt.UserRole, "dict_type")
                    categorized.add(dict_type)
            
            # 添加该模块下其他字典类型
            for dict_type in all_dict_types:
                if dict_type.startswith(module_name.replace("管理", "")) and dict_type not in categorized:
                    dict_item = QTreeWidgetItem(module_item, [dict_type])
                    dict_item.setData(0, Qt.UserRole, "dict_type")
                    categorized.add(dict_type)
        
        # 添加未分类的字典类型到"其他"模块
        uncategorized = [dt for dt in all_dict_types if dt not in categorized]
        if uncategorized:
            other_item = QTreeWidgetItem(self.module_tree, ["其他"])
            other_item.setData(0, Qt.UserRole, "module")
            for dict_type in uncategorized:
                dict_item = QTreeWidgetItem(other_item, [dict_type])
                dict_item.setData(0, Qt.UserRole, "dict_type")
    
    def on_module_item_clicked(self, item, column):
        """模块树项点击事件"""
        item_type = item.data(0, Qt.UserRole)
        if item_type == "dict_type":
            dict_name = item.text(0)
            self.load_dictionary_values_by_name(dict_name)
    
    def load_dictionary_data(self):
        """加载字典数据"""
        self.init_module_tree()
        # 默认加载第一个字典类型的值
        root = self.module_tree.invisibleRootItem()
        for i in range(root.childCount()):
            module_item = root.child(i)
            if module_item.childCount() > 0:
                first_dict_item = module_item.child(0)
                dict_name = first_dict_item.text(0)
                self.load_dictionary_values_by_name(dict_name)
                break
    
    def load_dictionary_values_by_name(self, dict_name):
        """根据字典名称加载字典值"""
        try:
            conn = self.db.get_connection()
            cursor = conn.cursor()
            # 使用DISTINCT去重
            cursor.execute('''
                SELECT DISTINCT dict_name, dict_value, description FROM dictionary 
                WHERE dict_name = ? ORDER BY dict_value
            ''', (dict_name,))
            data = cursor.fetchall()
            conn.close()
            
            self.dict_table.setRowCount(len(data))
            
            for row, item in enumerate(data):
                self.dict_table.setItem(row, 0, QTableWidgetItem(item[0]))
                self.dict_table.setItem(row, 1, QTableWidgetItem(item[1]))
                self.dict_table.setItem(row, 2, QTableWidgetItem(item[2] or ""))
            
            # 设置表格标题显示当前字典类型
            self.dict_table.setWindowTitle(f"字典值 - {dict_name}")
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载字典值失败：{str(e)}")
    
    def remove_duplicate_dictionary_data(self):
        """清理重复的字典数据"""
        try:
            conn = self.db.get_connection()
            cursor = conn.cursor()
            
            # 创建临时表存储去重后的数据
            cursor.execute('''
                CREATE TABLE dictionary_temp AS 
                SELECT DISTINCT dict_name, dict_value, description 
                FROM dictionary
            ''')
            
            # 删除原表
            cursor.execute('DROP TABLE dictionary')
            
            # 重命名临时表
            cursor.execute('ALTER TABLE dictionary_temp RENAME TO dictionary')
            
            # 重新创建索引
            cursor.execute('''
                CREATE INDEX IF NOT EXISTS idx_dict_name ON dictionary(dict_name)
            ''')
            
            conn.commit()
            conn.close()
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"清理重复字典数据失败：{str(e)}")
    
    def add_dictionary_value(self):
        """添加字典值"""
        dialog = DictionaryValueDialog(self, self.db)
        if dialog.exec_() == QDialog.Accepted:
            self.load_dictionary_data()

class DictionaryValueDialog(QDialog):
    def __init__(self, parent, db):
        super().__init__(parent)
        self.db = db
        
        self.setWindowTitle("添加字典值")
        self.setModal(True)
        self.resize(350, 200)
        
        self.init_ui()
        self.load_dictionary_types()
    
    def init_ui(self):
        """初始化界面"""
        layout = QVBoxLayout(self)
        
        # 表单布局
        form_layout = QFormLayout()
        
        # 字典名称
        self.dict_name_combo = QComboBox()
        self.dict_name_combo.setEditable(True)
        form_layout.addRow("字典名称*:", self.dict_name_combo)
        
        # 字典值
        self.dict_value_input = QLineEdit()
        form_layout.addRow("字典值*:", self.dict_value_input)
        
        # 描述
        self.description_input = QLineEdit()
        form_layout.addRow("描述:", self.description_input)
        
        layout.addLayout(form_layout)
        
        # 按钮
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)
    
    def load_dictionary_types(self):
        """加载字典类型"""
        try:
            conn = self.db.get_connection()
            cursor = conn.cursor()
            cursor.execute('SELECT DISTINCT dict_name FROM dictionary ORDER BY dict_name')
            dict_types = [row[0] for row in cursor.fetchall()]
            conn.close()
            
            self.dict_name_combo.addItems(dict_types)
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载字典类型失败：{str(e)}")
    
    def accept(self):
        """确定按钮事件"""
        dict_name = self.dict_name_combo.currentText().strip()
        dict_value = self.dict_value_input.text().strip()
        description = self.description_input.text().strip() or None
        
        # 验证必填字段
        if not all([dict_name, dict_value]):
            QMessageBox.warning(self, "警告", "请填写所有必填字段")
            return
        
        try:
            # 检查是否已存在相同的字典值
            conn = self.db.get_connection()
            cursor = conn.cursor()
            cursor.execute('''
                SELECT COUNT(*) FROM dictionary 
                WHERE dict_name = ? AND dict_value = ?
            ''', (dict_name, dict_value))
            count = cursor.fetchone()[0]
            conn.close()
            
            if count > 0:
                QMessageBox.warning(self, "警告", "该字典值已存在")
                return
            
            self.db.add_dictionary_value(dict_name, dict_value, description)
            super().accept()
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"添加失败：{str(e)}")